import os
import sys
import threading
import time

from flask import Flask, send_from_directory, jsonify
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtCore import QUrl
from datetime import datetime

# ===== 资源路径处理函数 =====
def resource_path(relative_path):
    """获取打包后资源的绝对路径"""
    if hasattr(sys, '_MEIPASS'):
        # 打包后的路径
        return os.path.join(sys._MEIPASS, relative_path)
    # 开发环境路径
    return os.path.join(os.path.abspath('.'), relative_path)

# ===== Flask后端部分 =====
backend = Flask(__name__, static_folder=resource_path('static'))

@backend.route('/api/data')
def get_data():
    return jsonify({
        'message': '这是来自内置后端的数据',
        'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    })

@backend.route('/<path:path>')
def serve_static(path):
    return send_from_directory(resource_path('static'), path)

@backend.route('/')
def index():
    return send_from_directory('static', 'index.html')

# 启动Flask后端的函数
def run_backend():
    backend.run(host='127.0.0.1', port=5000, debug=False, use_reloader=False)


# ===== PyQt前端部分 =====
class WebViewApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Vue3 + Flask 桌面应用')
        self.setGeometry(100, 100, 1000, 700)

        # 创建主布局
        central_widget = QWidget()
        layout = QVBoxLayout(central_widget)
        self.setCentralWidget(central_widget)
        self.setStyleSheet('background-color: rgb(230,230,250);')

        # 创建WebView并加载首页
        self.webview = QWebEngineView()
        layout.addWidget(self.webview)
        self.webview.load(QUrl('http://127.0.0.1:5000'))
        # self.webview.setFixedSize(1000, 700)
        self.setFixedSize(1000,700)
        layout.addWidget(self.webview)

        # 窗口关闭时退出程序
        self.closeEvent = self.on_close

    def on_close(self, event):
        """窗口关闭时停止后端线程"""
        sys.exit(0)


# ===== 主程序入口 =====
if __name__ == '__main__':
    # 调试输出
    print(f"当前工作目录: {os.getcwd()}")
    print(f"static目录是否存在: {os.path.exists(resource_path('static'))}")
    print(f"static/index.html是否存在: {os.path.exists(resource_path('static/index.html'))}")
    # time.sleep(5)

    # 确保static目录存在
    # if not os.path.exists('static'):
    #     print("错误：未找到static目录，请先打包前端")
    #     sys.exit(1)

    # 启动Flask后端线程
    backend_thread = threading.Thread(target=run_backend, daemon=True)
    backend_thread.start()

    # 启动PyQt应用
    app = QApplication(sys.argv)
    window = WebViewApp()
    window.show()
    sys.exit(app.exec_())